﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Data.Objects;

namespace Tst.Models
{
    public static class EntityHelper
    {
        public static void AttachUpdated(this ObjectContext context, EntityObject objectDetached)
        {
            if (objectDetached.EntityState == EntityState.Detached)
            {
                object currentEntityInDb = null;

                if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
                {
                    context.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);
                    context.ApplyReferencePropertyChanges(
                        (IEntityWithRelationships)objectDetached,                                                                                     
                        (IEntityWithRelationships)currentEntityInDb
                    ); 
                }
                else
                {
                    throw new ObjectNotFoundException();
                }
            }
        }

        public static void ApplyReferencePropertyChanges(this ObjectContext context,IEntityWithRelationships newEntity,IEntityWithRelationships oldEntity)
        {
            foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
            {
                var oldRef = relatedEnd as EntityReference;

                if (oldRef != null)
                {

                    var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
                    oldRef.EntityKey = newRef.EntityKey;
                }
            }
        }  
    }
}
